package com.csun.cmny.provider.device.watch;

import com.csun.cmny.provider.device.watch.entity.WatchConstant;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-04-03 20:35
 * @Description:
 */
@Data
@Slf4j
public class WatchCmdProcess extends Thread {

    /**
     * netty channel
     */
    private Channel channel;

    /**
     * 待处理消息
     */
    private String message;

    /**
     * 手环imei
     */
    private String deviceNo;

    /**
     * 是否在运行 true - 正在运行
     */
    private boolean running = true;

    /**
     * 任务Id
     */
    private String taskId;

    /**
     * 命令码
     */
    private String code;

    /**
     * 重发次数
     */
    private int times = 0;

    public WatchCmdProcess(String deviceNo, String message, String taskId, String code) {
        this.channel = WatchConstant.WATCH_CHANNEL_MAP.get(deviceNo);
        this.deviceNo = deviceNo;
        this.message = message;
        this.taskId = taskId;
        this.code = code;
    }

    @Override
    public void run() {

        while (running && times < WatchConstant.WATCH_INTERVAL_FREQUENCY) {

            if (channel != null && channel.isActive()) {
                times++;
                log.info("=====>   watch send message: {}", message);
                channel.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
                if (code.equals("048")) {	// 下发位置请求,只下发一次
                    break;
                }
            } else {
                log.warn("=====>   watch channel is null or inActive.");
            }

            try {
                sleep(WatchConstant.WATCH_INTERVAL_TIME);
            } catch (Exception e) {
                log.error("=====>   watch cmd process run error: {}", e.getMessage());
            }

        }
    }

}
